import { Swiper, SwiperRef, Toast } from 'antd-mobile'
import React, { useEffect, useState, useRef } from 'react'
import { useSearchParams, useNavigate, useLocation } from 'react-router-dom'
import http from '../../api'
import Loading from '../../components/publicComponents/Loading'
import { CircleDetailResult, CircleReplyList, CircleSpuList, CircleStoreList, CircleUser, VideoListResult } from '../../myTypes'
import style from './index.module.css'

interface VideoDataType {
  curVideoPlay: HTMLVideoElement | null
  love: number
  videoData: {
    circleId: string
    id: string
    type: string
    url: string
    videoCover: null | string
  }
  circleSpuList: Array<CircleSpuList>
  circleStoreList: Array<CircleStoreList>
  circleUser: CircleUser
  collectStatus: number
  isWrap: number
  headFigure: string
  area: string
  userId: string
  id: string
  status: number
  circleReplyList: Array<CircleReplyList>
  loveList: Array<string>
  total: number | null
  title: string
  content: string
}

export default function VideoPaly() {
  const [srarch] = useSearchParams()
  const navigate = useNavigate()
  const type = useLocation().state.type as string
  const circleId = srarch.get('circleid') as string
  const [videoList, setVideoList] = useState<Array<VideoDataType>>([])
  let [page, setPage] = useState(1)
  let [accountId, setAccountId] = useState<string>()
  const [hasMore, setHasMore] = useState(true)
  const swiper = useRef<SwiperRef>(null)
  const [isPlay, setIsPlay] = useState(false)

  useEffect(() => {
    const userId = localStorage.getItem('userId')
    if (userId) {
      accountId = userId
      setAccountId(userId)
      getVideoData()
    } else {
      navigate('/login')
    }
  }, [])

  async function getVideoData() {
    Toast.show({
      icon: <Loading />,
      duration: 0
    })
    let url = ''
    let params = {}
    if (type !== 'comment') {
      url = '/mty/circle/get'
      params = {
        accountId,
        circleId
      }
    } else {
      url = '/mty/comment/getDetail'
      params = {
        accountId: accountId,
        commentId: circleId
      }
    }
    const data = await http('get', url, params)
    Toast.clear()
    if (data) {
      const videoData = data.data as CircleDetailResult
      setVideoList((preData) => [...preData, createVideoData(videoData)])
    }
    getVideoList()
  }

  async function getVideoList() {
    if (hasMore) {
      const data = await http('get', '/mty/circle/getVideos', {
        accountId,
        pageSize: 12,
        pageNum: page,
        storeId: ''
      })
      if (data) {
        const videoList = data.data as VideoListResult
        const list = videoList.list.map((item) => createVideoData(item))
        setVideoList((preData) => [...preData, ...list])
        setPage((prePage) => prePage + 1)
        setHasMore(videoList.list.length > 0)
      }
    }
  }

  function createVideoData(videoData: CircleDetailResult): VideoDataType {
    return {
      curVideoPlay: null,
      love: videoData.love,
      videoData: {
        circleId: videoData.circleMaterialList[0].circleId,
        id: videoData.circleMaterialList[0].id,
        type: videoData.circleMaterialList[0].type,
        url: videoData.circleMaterialList[0].url,
        videoCover: videoData.circleMaterialList[0].videoCover
      },
      circleSpuList: videoData.circleSpuList,
      circleStoreList: videoData.circleStoreList,
      circleUser: videoData.circleUser,
      collectStatus: videoData.collectStatus,
      isWrap: videoData.isWrap,
      headFigure: videoData.headFigure,
      area: videoData.area,
      userId: videoData.userId,
      id: videoData.id,
      status: videoData.status,
      circleReplyList: videoData.circleReplyResult?.circleReplyList || [],
      loveList: videoData.circleReplyResult?.loveList || [],
      total: videoData.circleReplyResult?.total || null,
      title: videoData.title,
      content: videoData.content
    }
  }

  function curIndexChange(index: number) {
    videoList.forEach((item) => {
      const video = item.curVideoPlay
      if (video) {
        video.pause()
      }
    })
    const player = videoList[index].curVideoPlay
    if (player) {
      player.load()
      player.play()
      setIsPlay(true)
    }
    if (index === videoList.length - 1) {
      getVideoList()
    }
  }
  function playPause(item: VideoDataType) {
    const player = item.curVideoPlay
    if (!isPlay) {
      setIsPlay(true)
      player?.play()
    } else {
      setIsPlay(false)
      player?.pause()
    }
  }

  return (
    <div style={{ height: '100vh' }}>
      <div className={style['top-back']}>
        <div className={style['back']} onClick={() => navigate(-1)}>
          <img src="/static/arrow/icon-back-fff.png" alt="" />
        </div>
        <div className={style['more']}>
          <img src="/static/use/icon-btn-more-fff.png" alt="" />
        </div>
      </div>
      {videoList.length > 0 && (
        <Swiper
          ref={swiper}
          direction="vertical"
          style={{ height: '100vh' }}
          indicator={() => null}
          onIndexChange={(index) => {
            curIndexChange(index)
          }}
        >
          {videoList.map((item, index) => (
            <Swiper.Item key={index}>
              <div style={{ height: '100%', backgroundColor: 'black', position: 'relative' }}>
                {/* 用户头像和相关图标 */}
                <div className={style['user-info']}>
                  {/* 作者头像 */}
                  <div className={style['user-head']} style={{ backgroundImage: `url(${item.circleUser.head})` }}>
                    <div className={style['attention']} style={{ backgroundImage: 'url(/static/use/icon-add-circle.png)' }}></div>
                  </div>
                  {/* 点赞 */}
                  <div className={style['collection']}>
                    <div className={style['collection-icon']}>
                      {item.loveList.length === 0 && <img src="/static/use/icon-collect-88-fff.png" alt="" />}
                      {item.loveList.length > 0 && <img src="/static/use/icon-collect-88-red.png" alt="" />}
                    </div>
                    <div className={style['collection-number']}>{item.love}</div>
                  </div>
                  {/* 评论 */}
                  <div className={style['reply']}>
                    <div className={style['reply-icon']}>
                      <img src="/static/use/icon-comment-88-fff.png" alt="" />
                    </div>
                    <div>评论</div>
                  </div>
                  <div className={style['share']}>
                    <div className={style['share-icon']}>
                      <img src="static/use/icon-share-88-fff.png" alt="" />
                    </div>
                    <div>分享</div>
                  </div>
                </div>
                {/* 视频描述 */}
                <div className={style['video-desc']}>
                  {item.title && <div className={style['video-title']}>{item.title}</div>}

                  {/* content */}
                  {item.content && <div className={style['content']}>{item.content}</div>}

                  {(item.circleStoreList.length > 0 || item.circleSpuList.length > 0) && (
                    <div className={style['video-sup-list']}>
                      <div className={style['tip']}>圈友提及</div>
                      {item.circleStoreList.length > 0 && (
                        <div className={style['store']} style={{ backgroundImage: `url(${item.circleStoreList[0].headFigure})` }}>
                          {item.circleStoreList[0].storeName}
                        </div>
                      )}
                      {item.circleSpuList.length > 0 && (
                        <div className={style['spu-list-container']}>
                          {item.circleSpuList.map((c) => (
                            <div className={style['spu-list-item']} key={c.id}>
                              <img src={c.headFigure} alt="" />
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  )}
                </div>

                {/* 视频播放器 */}
                <div className={style['video-player']}>
                  {!isPlay && (
                    <div className={style['player-icon']}>
                      <img src="/static/use/icon-video-play-fff.png" alt="" />
                    </div>
                  )}

                  <video
                    ref={(e) => (item.curVideoPlay = e)}
                    onClick={() => {
                      playPause(item)
                    }}
                    onEnded={() => {
                      swiper.current?.swipeTo(index + 1)
                    }}
                    className={style['player']}
                    width={'100%'}
                    src={item.videoData.url}
                    poster={item.videoData.videoCover as string}
                  ></video>
                </div>
              </div>
            </Swiper.Item>
          ))}
        </Swiper>
      )}
    </div>
  )
}
